#include <stdio.h>

#include "GL/glew.h"
#include "GL/freeglut.h"

#include "utility.h"



void readFile(const char* filePath, char*& pBuffer, size_t& uByteSize)
{
    FILE* file = nullptr;

    errno_t errorCode = fopen_s(&file, filePath, "rb");
    if (0 != errorCode)
    {
        printf(Red, "fail to open file %s\n", filePath);
        throw;
    }

    // get the file size in byte
    fseek(file, 0, SEEK_END);
    uByteSize = ftell(file);

    // redirect to the beginner of the file
    fseek(file, 0, SEEK_SET);

    // get the file stream
    pBuffer = new char[uByteSize];
    fread(pBuffer, 1, uByteSize, file);

    fclose(file);
}


void writeFile(const char* filePath, const char* pBuffer, const size_t uByteSize)
{
    FILE* file = nullptr;

    errno_t errorCode = fopen_s(&file, filePath, "wb");
    if (0 != errorCode)
    {
        printf(Red, "fail to open file %s\n", filePath);
        throw;
    }

    size_t uWritten = fwrite(pBuffer, 1, uByteSize, file);

    ASSERT(uWritten == uByteSize);

    fclose(file);
}


unsigned int  write2VBO(const void* pData, const size_t size, GLenum buffType)
{
    // generate VBO
    GLuint vboBuffer;
    glGenBuffers(1, &vboBuffer);
    glBindBuffer(buffType, vboBuffer);
    glBufferData(buffType, size, pData, GL_STATIC_DRAW);

    printf("write to VBO: ");
    //printLastError();
    //printGraphicMemoryInfo();

    return vboBuffer;
}


unsigned int write2Texture(const void* pData)
{
    GLuint texID;
    GLuint iXdim = 10;
    GLuint iYdim = 10;
    GLuint iZdim = 10;
    glEnable(GL_TEXTURE_3D);
    glGenTextures(1, &texID);
    glBindTexture(GL_TEXTURE_3D, texID);

    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    
    glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB16F_ARB, iXdim, iYdim, iZdim, 0, GL_RGB, GL_FLOAT, pData);
    glBindTexture(GL_TEXTURE_3D,0);

    printf("write to texture info: ");
    //printLastError();
    //printGraphicMemoryInfo();

    glDisable(GL_TEXTURE_3D);

    if(GL_NO_ERROR != glGetError())
    {
        printf(Red, "After Load Texture error\n");
        throw;
    }

    return texID;
}

